﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Runtime.Remoting.Messaging;

namespace 委托的同步调用和异步调用
{
    public class Program
    {
        static void Main(string[] args)
        {
            //1.同步调用
            //SyncInvoke();
        
            //2.异步调用
            AsyncInvoke();
        }

        static int Add(int a, int b)
        {
            Console.WriteLine("Computing " + a + " + " + b + " ...");
            Thread.Sleep(3000);
            Console.WriteLine("Computing Complete.");
            return a + b;
        }

        static void SyncInvoke()
        {
            Console.WriteLine("**********SyncInvokeTest**************");
            AddHandler handler = new AddHandler(Add);
            int result = handler(1,2); //handler.Invoke(1, 2);
            Console.WriteLine("Do other work... ... ...");
            Console.WriteLine(result);
            Console.ReadLine();
        }

        static void AsyncInvoke()
        {
            Console.WriteLine("**********AsyncInvokeTest**************");
            AddHandler handler = new AddHandler(Add);
            IAsyncResult result = handler.BeginInvoke(1, 2, new AsyncCallback(AddComplete), "AsycState:OK");
            Console.WriteLine("Do other work... ... ...");
            Console.ReadLine();
        }

        static void AddComplete(IAsyncResult result)
        {
            AddHandler handler = (AddHandler)((AsyncResult)result).AsyncDelegate;
            Console.WriteLine(handler.EndInvoke(result));
            Console.WriteLine(result.AsyncState);
        }

    }
}
